package com.guchenbo.example.lock;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreDemo {

    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    final static Semaphore semaphore = new Semaphore(3);

    public static void main(String... args) throws Exception {
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            executor.submit(() -> {
                System.out.println("try acquire");
                try {
                    semaphore.acquire();
                    System.out.println("acquire");
//                    new WaitClientCloseServer().start(10000 + finalI);
Thread.sleep(3000);
                    System.out.println("close");
//                    remoteCall(finalI);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    semaphore.release();
                }

            });
        }
    }

    private static void remoteCall(int i) {
        System.out.println(String.format("%s - %s: %d", new Date(),
                Thread.currentThread(), i));
    }

}
